/* 1、查找本地存储，加载本地消息
 * 2、从服务器拉取未读信息并本地存储
 * 3、
 * */
//基本配置 开始

mui.init({
	gestureConfig: {
		tap: true,
		doubletap: true,
		longtap: true,
		swipe: true,
		drag: true,
		hold: true,
		release: true
	},
	beforeback: function() {
		document.activeElement.blur();
		bofang = true;
		if(document.getElementById('showTanChuang').innerHTML !=''){
			document.getElementById('showTanChuang').innerHTML = '';
			masks.close();
			return false;
		}
		setTimeout(function() {
			chat_config.rid = 0;
			MsgList.Msgdata = [];
			chat_config.newmegs = 0;
			chat_config.lahei = false;
		}, 300)
	}
});
//禁止页面右滑关闭
plus.webview.currentWebview().setStyle({
	'popGesture': 'hide'
});
//弹出软键盘默认高度减去键盘高度
plus.webview.currentWebview().setStyle({
	softinputMode: "adjustResize"
});
mui.previewImage();
var chat_config = {
	rid: null,
	rheadimg: '',
	user_headimg: user_info.headimg,
	user_id: user_info.user_id,
	payoff: 0,
	WebId_Msg: plus.webview.getWebviewById('Msg'),
	giftid: 0,
	lahei: false,
	newmegs: 0,
	title: '',
	ii: 30,
	lists: 0,
	imdata: [],
}
window.addEventListener('getheadimg', function(event) {
	user_info = JSON.parse(plus.storage.getItem("user_info"));
	chat_config.user_headimg = user_info.headimg;
})
var showKeyboard = function() {
	if($.os.ios) {
		var webView = plus.webview.currentWebview().nativeInstanceObject();
		webView.plusCallMethod({
			"setKeyboardDisplayRequiresUserAction": false
		})
	} else {
		var Context = plus.android.importClass("android.content.Context");
		var InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
		var main = plus.android.runtimeMainActivity();
		var imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
		imm.showSoftInput(main.getWindow().getDecorView(), InputMethodManager.SHOW_IMPLICIT)
	}
};

var ui = {
	body: document.querySelector('body'),
	footer: document.querySelector('footer'),
	footerRight: document.querySelector('.footer-right'),
	footerLeft: document.querySelector('.footer-left'),
	btnMsgType: document.querySelector('#msg-type'),
	boxMsgText: document.querySelector('#msg-text'),
	boxMsgSound: document.querySelector('#msg-sound'),
	btnMsgImage: document.querySelector('#msg-image'),
	areaMsgList: document.querySelector('#msg-list'),
	boxSoundAlert: document.querySelector('#sound-alert'),
	h: document.querySelector('#h'),
	closebox: document.querySelector('#closebox'),
	content: document.querySelector('.mui-content')
};

var MsgList = new Vue({
	el: '#msg-list',
	data: {
		Msgdata: [],
		uid: configs.user_id
	},
	computed: {
		classObject: function() {
			return {
				active: this.isActive && !this.error,
				'text-danger': this.error && this.error.type === 'fatal',
			}
		}
	},
	methods: {
		resetData: function() {
			Object.assign(this.$data, getDefaultData())
		},
		openblog: function(uid) {
			if(uid != configs.user_id && uid != 1) {
				openPersonalBlog(uid, chat_config.rheadimg, chat_config.title);
			}
		},
		opencall: function() {
			if(user_info.coin < 20) {
				mui.toast("颜值币不足，无法回拨！");
				openwetllvip(1);
			} else {
				mui.openWindow({
					url: '../html/page/Voice.html',
					id: 'Page_Voice',
					extras: {
						name: chat_config.title,
						headimg: chat_config.rheadimg,
						type: 'call'
					},
					createNew: false,
					show: {
						autoShow: true
					},
					waiting: {
						autoShow: false,
						title: '正在加载...'
					}
				})
			}
		}
	},
	directives: { 
		'scroll-bottom':function() {
			Vue.nextTick(function() {
				var scroitem = document.getElementById("msg-list");
				scroitem.scrollTop = scroitem.scrollHeight - scroitem.clientHeight;
			});
		}
	},
	filters: {
		Timeconversion: function(shijianchuo) {
			if(shijianchuo == 0) {
				var time = new Date()
			} else {
				var time = new Date(shijianchuo * 1000)
			}
			var m = time.getMonth() + 1;
			var d = time.getDate();
			var h = time.getHours();
			var mm = time.getMinutes();
			var s = time.getSeconds();
			return m + '月' + d + '日 ' + h + ':' + mm + ':' + s
		},
		liwpic: function(value) {
			return "../img/gift/" + value + ".png"
		}
	}
});

//基本配置 结束

if(!isallpay()) {
	document.getElementById("yuyin").style.display = "none";
	document.getElementById("liwulist").style.display = "none";
}

var html_title = document.getElementsByClassName('mui-title')[0];
//mui('.mui-title');
/*页面流程 开始 */
window.addEventListener('getmessage', function(event) {
	chat_config.rid = event.detail.id;
	chat_config.title = event.detail.title;
	chat_config.rheadimg = event.detail.rheadimg;
	html_title.innerHTML = chat_config.title;
	if(chat_config.user_headimg == "") {
		chat_config.user_headimg = '../img/function/mtoux.jpg';
	}
	if(islahei(chat_config.rid)) {
		chat_config.lahei = true;
		mui.toast('您已将对方拉黑！');
	} else {

	}

	var imstring = plus.storage.getItem('IM' + chat_config.rid);
	if(imstring) {
		MsgList.Msgdata = JSON.parse(imstring);
	}
});

window.addEventListener('Msg_NowTime', function(event) {
	var sid = event.detail.sid;
	if(sid == chat_config.rid) {
		var imstring = plus.storage.getItem('IM' + chat_config.rid);
		if(imstring) {
			MsgList.Msgdata = JSON.parse(imstring);
		}
	}
});
//监听清空资料
document.addEventListener('MSGqingkong', function(event) {
	if(event.detail.sid == chat_config.rid) {
		MsgList.Msgdata = [];
	}
});
/*页面流程 开始 */

/*基本功能 开始 */
var MIN_SOUND_TIME = 800;

ui.footerRight.addEventListener('touchstart', function(event) {

	if(ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
		msgTextFocus();
		event.preventDefault()
	}
	msgTextFocus();
});
ui.footerRight.addEventListener('touchmove', function(event) {

	if(ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
		msgTextFocus();
		event.preventDefault()
	}
});
function unhtml(str) {
    return str ? str.replace(/[<">']/g, function(a) {
        return {
            '<': '&lt;',
            '"': '&quot;',
            '>': '&gt;',
            "'": '&#39;'
        }[a]
    }) : '';
};
ui.footerRight.addEventListener('release', function(event) {
	if(ui.btnMsgType.classList.contains('mui-icon-paperplane')) {
		ui.boxMsgText.focus();
		setTimeout(function() {
			ui.boxMsgText.focus()
		}, 150);
		
		ui.boxMsgText.value = unhtml(ui.boxMsgText.value);
		
		send({
			type: 0,
			content: ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '<br/>')
		});
		ui.boxMsgText.value = '';
		mui.trigger(ui.boxMsgText, 'input', null)
	} else if(ui.btnMsgType.classList.contains('mui-icon-mic')) {
		ui.btnMsgType.classList.add('mui-icon-compose');
		ui.btnMsgType.classList.remove('mui-icon-mic');
		ui.boxMsgText.style.display = 'none';
		ui.boxMsgSound.style.display = 'block';
		ui.boxMsgText.blur();
		document.body.focus()
	} else if(ui.btnMsgType.classList.contains('mui-icon-compose')) {
		ui.btnMsgType.classList.add('mui-icon-mic');
		ui.btnMsgType.classList.remove('mui-icon-compose');
		ui.boxMsgSound.style.display = 'none';
		ui.boxMsgText.style.display = 'block';
		ui.boxMsgText.focus();
		setTimeout(function() {
			ui.boxMsgText.focus()
		}, 150)
	}
}, false);

function msgTextFocus() {
	ui.boxMsgText.focus();
	setTimeout(function() {
		ui.boxMsgText.focus();
	}, 150);

}
ui.footerLeft.addEventListener('tap', function(event) {
	var btnArray = [{
		title: "拍照"
	}, {
		title: "从相册选择"
	}];
	plus.nativeUI.actionSheet({
		title: "选择照片",
		cancel: "取消",
		buttons: btnArray
	}, function(e) {
		var index = e.index;
		switch(index) {
			case 0:
				break;
			case 1:
				var cmr = plus.camera.getCamera();
				cmr.captureImage(function(path) {
					send({
						type: 1,
						content: "file://" + plus.io.convertLocalFileSystemURL(path)
					})
				}, function(err) {});
				break;
			case 2:
				plus.gallery.pick(function(path) {
					send({
						type: 1,
						content: path
					})
				}, function(err) {}, null);
				break
		}
	})
}, false);
var setSoundAlertVisable = function(show) {
	if(show) {
		ui.boxSoundAlert.style.display = 'block';
		ui.boxSoundAlert.style.opacity = 1
	} else {
		ui.boxSoundAlert.style.opacity = 0;
		setTimeout(function() {
			ui.boxSoundAlert.style.display = 'none'
		}, 200)
	}
};
var recordCancel = false;
var recorder = null;
var audio_tips = document.getElementById("audio_tips");
var startTimestamp = null;
var stopTimestamp = null;
var stopTimer = null;
var footerPadding = ui.footer.offsetHeight - ui.boxMsgText.offsetHeight;
ui.boxMsgSound.addEventListener('hold', function(event) {
	recordCancel = false;
	if(stopTimer) {
		clearTimeout(stopTimer)
	}
	audio_tips.innerHTML = "手指上划，取消发送";
	ui.boxSoundAlert.classList.remove('rprogress-sigh');
	setSoundAlertVisable(true);
	recorder = plus.audio.getRecorder();
	if(recorder == null) {
		plus.nativeUI.toast("不能获取录音对象");
		return
	}
	startTimestamp = (new Date()).getTime();
	recorder.record({
		filename: "_doc/audio/"
	}, function(path) {
		if(recordCancel) {
			return
		}
		send({
			type: 2,
			content: path
		})
	}, function(e) {
		plus.nativeUI.toast("录音时出现异常: " + e.message)
	})
}, false);
ui.body.addEventListener('drag', function(event) {
	if(Math.abs(event.detail.deltaY) > 50) {
		if(!recordCancel) {
			recordCancel = true;
			if(!audio_tips.classList.contains("cancel")) {
				audio_tips.classList.add("cancel")
			}
			audio_tips.innerHTML = "松开手指，取消发送"
		}
	} else {
		if(recordCancel) {
			recordCancel = false;
			if(audio_tips.classList.contains("cancel")) {
				audio_tips.classList.remove("cancel")
			}
			audio_tips.innerHTML = "手指上划，取消发送"
		}
	}
}, false);
ui.boxMsgSound.addEventListener('release', function(event) {
	if(audio_tips.classList.contains("cancel")) {
		audio_tips.classList.remove("cancel");
		audio_tips.innerHTML = "手指上划，取消发送"
	}
	stopTimestamp = (new Date()).getTime();
	if(stopTimestamp - startTimestamp < MIN_SOUND_TIME) {
		audio_tips.innerHTML = "录音时间太短";
		ui.boxSoundAlert.classList.add('rprogress-sigh');
		recordCancel = true;
		stopTimer = setTimeout(function() {
			setSoundAlertVisable(false)
		}, 800)
	} else {
		setSoundAlertVisable(false)
	}
	recorder.stop()
}, false);
ui.boxMsgSound.addEventListener("touchstart", function(e) {
	//	return false;
	e.preventDefault()
});

ui.boxMsgText.addEventListener('input', function(event) {
	ui.btnMsgType.classList[ui.boxMsgText.value == '' ? 'remove' : 'add']('mui-icon-paperplane');
	ui.btnMsgType.setAttribute("for", ui.boxMsgText.value == '' ? '' : 'msg-text');
	ui.h.innerText = ui.boxMsgText.value.replace(new RegExp('\n', 'gm'), '\n-') || '-';
	ui.footer.style.height = (ui.h.offsetHeight + footerPadding) + 'px';
	ui.content.style.paddingBottom = ui.footer.style.height;
});
//点击输入框弹出键盘
var focus = false;
ui.boxMsgText.addEventListener('tap', function(event) {
	ui.boxMsgText.focus();
	setTimeout(function() {
		ui.boxMsgText.focus();
	}, 0);
	focus = true;
	setTimeout(function() {
		focus = false;
	}, 1000);
	event.detail.gesture.preventDefault();
});
//点击消息内容 关闭键盘
ui.areaMsgList.addEventListener('click', function(e) {
	if(focus) {
		ui.boxMsgText.blur();
	}
})

//发送
var send = function(msg) {
	if(chat_config.lahei && msg.type != 5) {
		mui.toast('您已将对方拉黑，无法发送消息！');
		return;
	} else {
		showWaiting('发送中…')
		switch(msg.type) {
			case 0:
				msg_post_data(msg);
				break;
			case 1:
				appendFile(msg);
				break;
			case 2:
				Audio2dataURL(msg)
				break;
			case 4:
				fasongmsg(msg, 1);
				break;
			case 5:
				fasongmsg(msg, 1);
				break;
			default:
				break
		}
	}
};
var posturl = getApiUrl('http://www.jiaoyou0.cn', 'chats/postMessage');

function msg_post_data(msg) {
	mui.post(posturl, {
		'receive_uid': chat_config.rid,
		'type': msg.type,
		'content': msg.content
	}, function(data) {
		if(data.code == 200) {
			msg.content = data.data;
			fasongmsg(msg, 1)
		} else if(data.code == 203) {
			fasongmsg(msg, 3)
		} else {
			fasongmsg(msg, 0)
		}
	}, 'json');
}

function appendFile(msg) {
	var img = new Image();
	img.src = msg.content;
	img.onload = function() {
		var w = this.width,
			h = this.height,
			scale = w / h;
		w = 480 || w;
		h = w / scale;
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		canvas.width = w;
		canvas.height = h;
		ctx.drawImage(this, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8);
		msg.content = base64;
		msg_post_data(msg);
	}
}

window.addEventListener('sendgift', function(event) {
	send({
		type: 4,
		content: event.detail.giftid
	})
})

function Audio2dataURL(msg) {
	plus.io.resolveLocalFileSystemURL(msg.content, function(entry) {
		entry.file(function(file) {
			var reader = new plus.io.FileReader();
			reader.onloadend = function(e) {
				msg.content = e.target.result;
				msg_post_data(msg);
			};
			reader.readAsDataURL(file);
		}, function(e) {
			mui.toast('发送失败，请重试！')
		})
	})
}

function fasongmsg(msg, sendof) {

	plus.nativeUI.closeWaiting();
	if(sendof == 1) {
		var sendtime = Date.parse(new Date()) / 1000;
		var media_url, giftid;
		if(msg.type == 0) {
			media_url = '';
			giftid = 0;
//			msg.content.replace(new RegExp('\<br\/\>'), '');
		} else if(msg.type == 1 || msg.type == 2) {
			media_url = msg.content;
			giftid = 0;
			msg.content = '';
		} else if(msg.type == 4) {
			media_url = '';
			giftid = msg.content;
			msg.content = '';
		}
		MsgList.Msgdata.push({
			send_uid: configs.user_id,
			nick_name: chat_config.title,
			reply_type: msg.type,
			content: msg.content,
			headimg: chat_config.user_headimg,
			media_url: media_url,
			giftid: giftid,
			send_time: sendtime
		});
		plus.storage.setItem('IM' + chat_config.rid, JSON.stringify(MsgList.Msgdata));
		if(!chat_config.WebId_Msg) {
			chat_config.WebId_Msg = plus.webview.getWebviewById('Msg')
		}
		mui.fire(chat_config.WebId_Msg, 'Chat_back', {
			send_uid: chat_config.rid,
			nick_name: chat_config.title,
			reply_type: msg.type,
			headimg: chat_config.rheadimg,
			send_time: sendtime,
			content: msg.content.replace(/<\/?[^>]*>/g, '…')
		});
	} else if(sendof == 2) {
		openwetllvip(2);
	} else if(sendof == 3) {
		ui.boxMsgText.blur();
		openwetllvip(2);
	} else {
		document.activeElement.blur();
		ui.boxMsgText.blur();
		openwetllvip(2);
	}
}

function openwetllvip(type) {
	if(type==1){
		showTanChuang('发送视频聊天申请需要消耗颜值币哦，你的颜值币余额不足啦！','看小姐姐','不看了',type,'page/wallet.html')
	}else{
		showTanChuang('VIP会员可以无限畅聊哦，快快升级和女神索要联系方式吧！','开通畅聊','离开女神',type,'page/wallet.html')
	}
}


var footerPadding = ui.footer.offsetHeight - ui.boxMsgText.offsetHeight;
var bofang = true;

mui('#msg-list').on('tap', '.msg-sounds', function() {
	if(!bofang) {
		return
	} else {
		bofang = false
	}
	var playState = this.querySelector('.play-state');
	if(configs.device == 1) {
		var audio = this.querySelector('audio');
		playState.innerText = '正在播放';
		audio.play();
		audio.addEventListener('ended', function() {
			playState.innerText = '点击播放';
			bofang = true
		}, false)
	} else {
		var msgType = this.getAttribute('msg-type');
		var msgContent = this.getAttribute('msg-content');
		console.log(msgContent )
		player = plus.audio.createPlayer(msgContent);
		playState.innerText = '正在播放...';
		player.play(function() {
			playState.innerText = '点击播放';
			bofang = true
		}, function(e) {
			playState.innerText = '点击播放';
			bofang = true
		})
	}
});

/*跳转礼物页面*/
document.getElementById("liwulist").onclick = function() {
	mui.openWindow({
		url: 'page/gift.html',
		id: 'gift',
		extras: {
			rid: chat_config.rid
		},
		createNew: false,
		show: {
			autoShow: true,
			aniShow: "slide-in-bottom"
		}
	})
}

/*跳转礼物页面结束*/

///*回复并索要联系方式 页面跳转*/
//mui('#closebox')[0].addEventListener('tap', function(event) {
//	mui.toast('开通VIP会员可无限畅聊');
//	openwetllvip(2);
//}, false);
/*回复并索要联系方式 页面结束*/
/*语音通话 页面跳转*/
mui('#yuyin')[0].addEventListener('tap', function() {
	if(chat_config.lahei) {
		mui.toast('您已将对方拉黑，无法拨打！');
		return;
	}
	mui.openWindow({
		url: '../html/page/Voice.html',
		id: 'Page_Voice',
		extras: {
			name: chat_config.title,
			headimg: chat_config.rheadimg,
			type: 'call'
		},
		createNew: false,
		show: {
			autoShow: true
		},
		waiting: {
			autoShow: false,
			title: '正在加载...'
		}
	})
});
/*语音通话 页面跳转结束 */

//bindMsgList();
window.addEventListener('resize', function() {
	ui.areaMsgList.scrollTop = ui.areaMsgList.scrollHeight + ui.areaMsgList.offsetHeight
}, false);

//右上角拉黑处理
document.getElementById("anniu").onclick = function() {
	mui.openWindow({
		url: 'page/Hei_ziliao.html',
		id: 'ziliao',
		extras: {
			name: chat_config.title,
			headimg: chat_config.rheadimg,
			user_id: chat_config.rid
		},
		createNew: false,
		show: {
			autoShow: true
		},
		waiting: {
			autoShow: true,
			title: '正在加载...'
		}
	})
}

//清空所有数据
function killall() {
	chat_config.rid = 0;
	MsgList.Msgdata = {};
	chat_config.newmegs = 0;
}

/*基本功能 结束 */